package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApCollectionService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.feign.article.IArticleClient;
import com.heima.feign.article.IUserClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;

import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.user.dtos.ArticleInfoDto;
import com.heima.model.user.dtos.LikesBehaviorDto;
import com.heima.model.user.dtos.UnLikesBehaviorDto;
import com.heima.model.user.dtos.readBehaviorDto;
import com.heima.model.user.pojos.ApCollection;
import com.heima.model.user.pojos.ApuUerFollow;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.nntp.Article;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;
    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //更新数据库阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //计算文章分值
        Integer score = computeScore(apArticle);
        score=score*3;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);



    }

    /**\
     * 替换热点数据
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        String jsonHotArticleVo = cacheService.get(s);
        if (StringUtils.isNotBlank(jsonHotArticleVo)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonHotArticleVo, HotArticleVo.class);
            boolean flag=true;
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())){
                    hotArticleVo.setScore(score);
                    flag=false;
                    break;
                }
            }
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo articleVo = hotArticleVoList.get(hotArticleVoList.size() - 1);

                    if (articleVo.getScore() < score) {
                        hotArticleVoList.remove(articleVo);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }

                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s,JSON.toJSONString(hotArticleVoList));


        }

    }

    /**
     * 计算每一篇文章的的分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }

    /**
     * 更新数据库阅读、点赞、收藏、评论的数量
     * @param mess
     * @return
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setLikes(apArticle.getLikes()==null?0:apArticle.getLikes()+mess.getLike());
        apArticle.setComment(apArticle.getComment()==null?0:apArticle.getComment()+mess.getComment());
        apArticle.setViews(apArticle.getViews()==null?0:apArticle.getViews()+mess.getView());
        apArticle.setCollection(apArticle.getCollection()==null?0:apArticle.getCollection()+mess.getCollect());
        updateById(apArticle);
        return apArticle;
    }

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        Integer size = dto.getSize();
        if (size != null || size != 0) {
            size = 10;
        }
        size = Math.min(size, MAX_PAGE_SIZE);

        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }


        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);

        return ResponseResult.okResult(apArticles);
    }

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {

        //是首页就返回redis中的热点数据
        if (firstPage) {
            String JosnStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(JosnStr)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(JosnStr, HotArticleVo.class);
                log.info("加载了热点数据");
                return ResponseResult.okResult(hotArticleVoList);
            }
        }

        return load(type, dto);
    }

    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
//        apArticle.setPublishTime(new Date());

        if (dto.getId() == null) {
            //保存文章
            save(apArticle);
            //保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);
            //保存 文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        } else {
            //修改  文章
            updateById(apArticle);

            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);

        }
        //生成模板上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());


        //3.结果返回  文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    @Autowired
    private CacheService cacheService;
    @Autowired
    private ApCollectionService apCollectionService;
    //    @Autowired
//    private IArticleClient iArticleClient;
    @Autowired
    private IUserClient iUserClient;

    @Override
    @Transactional
    public ResponseResult sjhx(ArticleInfoDto dto) {
        Integer id = AppThreadLocalUtil.getUser().getId();
        StringRedisTemplate stringRedisTemplate = cacheService.getstringRedisTemplate();
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        //是否点赞
        String likesBehaviorDtoString = (String) opsForHash.get("yongHuXingWei:" + id + "_userId", dto.getArticleId().toString() + "_dz");
        LikesBehaviorDto likesBehaviorDto = JSON.parseObject(likesBehaviorDtoString, LikesBehaviorDto.class);
        boolean fals1 = likesBehaviorDto != null && likesBehaviorDto.getOperation() == 0 ? true : false;
        //是否不喜欢
        String unLikesBehaviorDtoString = (String) opsForHash.get("yongHuXingWei:" + id + "_userId", dto.getArticleId().toString() + "_bxh");
        UnLikesBehaviorDto unLikesBehaviorDto = JSON.parseObject(unLikesBehaviorDtoString, UnLikesBehaviorDto.class);
        boolean fals2 = unLikesBehaviorDto != null && unLikesBehaviorDto.getType() == 0 ? true : false;
        //是否收藏
        LambdaQueryWrapper<ApCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApCollection::getEntryId, id);
        wrapper.eq(ApCollection::getArticleId, dto.getArticleId());
        ApCollection apCollection = apCollectionService.getOne(wrapper);
        boolean fals3 = apCollection != null ? true : false;
        //是否关注
        ApuUerFollow apuUerFollow = iUserClient.gz(dto, (long) id);
        boolean fals4 = apuUerFollow != null ? true : false;
        //封装结果
        Map<String, Object> map = new HashMap<>();
        map.put("islike", fals1); //点赞
        map.put("isunlike", fals2);  //不喜欢
        map.put("iscollection", fals3); //收藏
        map.put("isfollow", fals4);   //关注

        return ResponseResult.okResult(map);
    }

    @Override
    public void ydnum(readBehaviorDto dto) {
        if (dto.getArticleId() != null) {
            ApArticle apArticle = apArticleMapper.selectById(dto.getArticleId());

            if (apArticle != null) {
                if (apArticle.getViews() == null) {
                    apArticle.setViews(0);
                }
                apArticle.setViews(apArticle.getViews() + 1);
                apArticleMapper.updateById(apArticle);
                log.info("阅读数据更新");
            }
        }

    }

    @Override
    public void dznum(LikesBehaviorDto dto) {
        if (dto.getArticleId() != null && dto.getOperation() != null) {
            ApArticle apArticle = apArticleMapper.selectById(dto.getArticleId());

            if (apArticle != null) {
                if (apArticle.getLikes() == null) {
                    apArticle.setLikes(0);
                }
                if (dto.getOperation() == 0) {
                    apArticle.setLikes(apArticle.getLikes() + 1);
                } else if (dto.getOperation() == 1) {
                    apArticle.setLikes(apArticle.getLikes() - 1);
                }
                apArticleMapper.updateById(apArticle);
                log.info("点赞数据更新");
            }
        }
    }

}